package com.sxt.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import com.sxt.domain.User;

/**
 * 使用JDK序列化
 * 
 * @author Liushuangxi 序列化 : 代表对象由一种形式，转为另一种形式
 */
public class SerializableUtil {
	/**
	 * 正向序列化 Object - > byte[]
	 */
	public static byte[] serializable(Object obj) {
		ByteArrayOutputStream byteArrayOutputStream = null;
		ObjectOutputStream objectOutputStream = null;
		byte[] bs = null;
		try {
			byteArrayOutputStream = new ByteArrayOutputStream();
			objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
			objectOutputStream.writeObject(obj); 
			// 将对象写入到内存里面
			objectOutputStream.flush();
			bs = byteArrayOutputStream.toByteArray();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return bs;
	}

	/**
	 * 逆向序列化
	 */
	public static Object deSerializable(byte[] bs) {
		ByteArrayInputStream byteArrayInputStream = null;
		ObjectInputStream objectInputStream = null;
		Object result = null;
		try {
			byteArrayInputStream = new ByteArrayInputStream(bs);
			objectInputStream = new ObjectInputStream(byteArrayInputStream);
			result = objectInputStream.readObject();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			closes(objectInputStream, byteArrayInputStream); // 关闭资源
		}
		return result;
	}

	/**
	 * 关闭资源的操作
	 * 
	 * @param closes
	 */
	public static void closes(Closeable... closes) {
		for (Closeable closeable : closes) {
			if (null != closeable) {
				try {
					closeable.close();
				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					closeable = null; // GC 回收
				}
			}
		}
	}
}
